import { DeleteModal } from '@/components/Modals';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Space, Typography } from 'antd';
import { useEffect, useMemo, useRef, useState } from 'react';
import Form from './Form';
import api from './request';

function ShopClassifyManagement() {
  const actionRef = useRef<ActionType>();
  const [isShowModal, setIsShowModal] = useState(false);
  const [curData, setCurData] = useState<Partial<ShopClassifyManagementApi.InfoResponse>>({});
  const [list, setList] = useState<ShopClassifyManagementApi.InfoResponse[]>([]);
  const getAllList = async () => {
    const data = await api.getAllList();
    setList(data);
  };

  useEffect(() => {
    getAllList();
  }, []);

  const setState = (state: boolean, data?: ShopClassifyManagementApi.InfoResponse) => {
    setCurData(data || {});
    setIsShowModal(state);
  };
  const removeRequest = async (params: ShopClassifyManagementApi.DeleteParams) => {
    const data = await api.remove(params);
    if (data.success) {
      getAllList();
      setState(false);
    }
  };
  const onConfirmRemove = () => {
    const { id = '' } = curData;
    removeRequest([id]);
  };
  const onCancelRemove = () => {
    setState(false);
  };

  const columns = useMemo(() => {
    const tableColumns: ProColumns<ShopClassifyManagementApi.InfoResponse>[] = [
      {
        title: '门店分类',
        dataIndex: 'classifyName',
        ellipsis: true,
        align: 'center',
      },
      {
        title: '操作',
        hideInSearch: true,
        align: 'center',
        render(_, record) {
          return (
            <Space>
              <Typography.Link>
                <Form isEdit data={record} onSuccess={() => getAllList()} />
              </Typography.Link>
              <Typography.Link>
                <Button danger type="link" onClick={() => setState(true, record)}>
                  删除
                </Button>
              </Typography.Link>
            </Space>
          );
        },
      },
    ];
    return tableColumns;
  }, []);

  return (
    <PageContainer>
      <ProTable
        size="small"
        bordered
        rowKey="id"
        actionRef={actionRef}
        showHeader={true}
        headerTitle={false}
        search={false}
        options={false}
        pagination={false}
        toolBarRender={() => [
          <Button key="search" type="primary" onClick={getAllList}>
            查询
          </Button>,
          <Form key="add" isEdit={false} onSuccess={() => getAllList()} />,
        ]}
        columns={columns}
        dataSource={list}
        expandable={{ defaultExpandAllRows: true }}
      />
      <DeleteModal
        open={isShowModal}
        content="确认删除吗？"
        onOk={onConfirmRemove}
        onCancel={onCancelRemove}
      />
    </PageContainer>
  );
}

export default ShopClassifyManagement;
